import React, {FC, useCallback, useEffect, useMemo, useState} from "react";
import {isDevelopment, isFunction, treeMap, tryFunction} from "../utils";
import {getLocale} from "../../i18n/i18n";
import GlobalIcon from "./GlobalIcon.tsx";
import {BtnFlow} from "../services/BtnFlowService.tsx";
import {openEditUrl} from "../services/MenuService.tsx";
import {Menu} from "antd";
import "./css/GlobalBtn.less";

interface GlobalBtnProps {
    menus: any[],
    dataSource: any,
    className?: string,
    isShowIcon?: boolean
}

const GlobalBtn: FC<GlobalBtnProps> = (props) => {

    const [menuList, setMenuList] = useState<any[]>([]);

    useEffect(() => {
        const {menus = [], isShowIcon = true}: { menus: any[], isShowIcon: boolean } = props;
        let newMenus: any[] = treeMap(menus, (child: any[], item: any) => {
            let menuConfig: any = {}, isReturn: boolean = true;
            if (item.config) {
                tryFunction(() => {
                    eval("window.menuConfig =" + item.config)
                    menuConfig = window.menuConfig || {};
                });
                if (isFunction(menuConfig.isShow)) {
                    isReturn = menuConfig.isShow(props.dataSource || {})
                }
            }
            return isReturn ? {
                label: getLocale(item.zhCn, item.usEn, item.ptBr),
                title: getLocale(item.zhCn, item.usEn, item.ptBr),
                id: item.id,
                key: item.id,
                popupClassName: child.length ? "sf_core_sub_list_btn" : "",
                icon: isShowIcon ? <GlobalIcon name={item.icon || "icon-setting"}/> : null,
                operate: item.operate,
                parent: item.parentId,
                children: child.length ? child : null
            } : null
        });

        setMenuList(newMenus);
    }, [props.menus, props.dataSource, props.isShowIcon]);

    const menuClick: Function = useCallback(({item, key, domEvent}: { item: any, key: string, domEvent: any }) => {
        if (domEvent.altKey && isDevelopment()) {
            openEditUrl(key)
            return
        }
        BtnFlow(domEvent.target, props.dataSource, item.props).flow();
    }, [props]);

    const renderGlobalBtn = useMemo(() => {
        if (!menuList.length) {
            return null;
        }
        const {className = ""}: { className: string } = props;
        return (<Menu
            className={"sf_core_list_btn " + className}
            mode={"horizontal"}
            selectable={false}
            items={menuList}
            onClick={menuClick}
        />)
    }, [props, menuList]);

    return (renderGlobalBtn);
};

export default React.memo(GlobalBtn);